<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect,
  useMessage,
  NFlex,
  NAvatar, NSelect
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import { getToken } from '@/utils'
import { formatDate, renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'

defineOptions({ name: '素材管理' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE
import default_image from "@/assets/images/mz.jpg"

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '素材',
  initForm: {},
  doCreate: api.createContents,
  doUpdate: api.updateContents,
  doDelete: api.deleteContents,
  refresh: () => $table.value?.handlerefresh(),
})
const data = reactive({
  token: getToken(),
  uploadAction: base_path+'api/content/contents/file',
  uploadActions: base_path+'api/content/contents/files',
  TypeData: [
    {
      label: '图文',
      value: 1,
    },
    {
      label: '视频',
      value: 2,
    }
  ],
  tag_options: [
    {
      label: '推荐',
      value: '推荐',
    },
    {
      label: '加精',
      value: '加精',
    }
  ],
  parentData: [],
  deptOption: [],
  gotypeData: [],
  fileList: [],
  upload: null,
  fileListLength: 0
});
const deptOption = ref([])

onMounted(() => {
  api.getCategoryTree().then((res) => (deptOption.value = res.data))
  api.getGoType().then((res) => (data.gotypeData = res.data))
  $table.value?.handleSearch()
})


//上传封面图
const message = useMessage();
const customRequestMethod = (options) => {
  const { file } = options.file;
  const formData = new FormData();
  formData.append('file', file);
  fetch(data.uploadAction, {
    method: 'POST',
    headers: options.headers,
    body: formData,
  })
      .then((response) => response.json())
      .then((data) => {
        console.log(data, 'datatat');
        if (data.code === 200) {
          modalForm.value.cover = data.data.url
          message.success('封面图上传成功');
          options.onProgress(data);
        }else{
          message.error(data.msg);
        }
      })
}
const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },

  },
  {
    title: '标题',
    key: 'title',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
  },
  {
    title: '排序',
    key: 'order',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '类型',
    key: 'type_name',
    width: 30,
    align: 'center',
  },
  {
    title: '分类',
    key: 'parent_data.name',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },

  {
    title: '标签',
    key: 'tags',
    align: 'left',
    width:60,
    ellipsis: { tooltip: true },
    render(row) {
      const tags = row.tags ?? []
      const group = []
      for (let i = 0; i < tags.length; i++)
        group.push(
            h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '0px 3px' } }, { default: () => tags[i] })
        )
      return h('span', group)
    },
  },
  {
    title: '封面图',
    key: 'cover',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
    render(row) {
      return h(NFlex, {},
          [h(NImage, {
            src: row.cover,
            width: 30,
            height : 30,
            fallbackSrc: default_image,
          })]
      )

    },
  },
  {
    title: '创建时间',
    key: 'created_at',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '禁用',
    key: 'state',
    width: 50,
    align: 'center',
    render(row) {
      return h(NSwitch, {
        size: 'small',
        rubberBand: false,
        value: row.state,
        loading: !!row.publishing,
        checkedValue: false,
        uncheckedValue: true,
        onUpdateValue: () => handleUpdateDisable(row),
      })
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 100,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
               handleEdit(row)
                    if(!modalForm.value.files){
                      modalForm.value.files = []
                    }
              },
            },
              {
                default: () => '编辑',
                icon: renderIcon('material-symbols:edit', {size: 16}),
              }
          ),
            [[vPermission, 'post/api/content/contents/update']]
        ),
        h(
            NPopconfirm,
            {
              onPositiveClick: () => handleDelete({data_id: row.id}, false),
              onNegativeClick: () => {
              },
            },
            {
              trigger: () =>
                  withDirectives(
                      h(
                          NButton,
                          {
                            size: 'small',
                            type: 'error',
                          },
                          {
                            default: () => '删除',
                            icon: renderIcon('material-symbols:delete-outline', {size: 16}),
                          }
                      ),
                      [[vPermission, 'delete/api/content/contents/delete']]
                  ),
              default: () => h('div', {}, '确定删除该素材吗?'),
            }
        ),
      ]
    },
  },
]

// 修改用户禁用状态
async function handleUpdateDisable(row) {
  if (!row.id) return
  row.publishing = true
  row.state = row.state === false
  row.publishing = false
  try {
    await api.updateContents(row)
    $message?.success(row.state ? '已取消禁' : '已禁用')
    $table.value?.handleSearch()
  } catch (err) {
    // 有异常恢复原来的状态
    row.state = row.state === false ? true : false
  } finally {
    row.publishing = false
  }
}

let lastClickedNodeId = null
const validateAddUser = {
  title: [
    {
      required: true,
      message: '请输入标题',
      trigger: ['input', 'blur'],
    },
  ],
  parent: [
    {
      required: true,
      message: '素材分类',
      trigger: ['blur', 'change'],
      type: 'number',
    },
  ],
  type: [
    {
      required: true,
      message: '素材类型',
      trigger: ['blur', 'change'],
      type: 'number',
    },
  ],
}

const nodeProps = ({option}) => {
  return {
    onClick() {
      if (lastClickedNodeId === option.id) {
        $table.value?.handleSearch()
        lastClickedNodeId = null
      } else {
        queryItems.value.parent_id = option.id
        $table.value?.handleSearch()
      }
    },
  }
}

const handleFinish = ({
                        file,
                        event
                      }) => {

  let data = (event?.target).response
  data = JSON.parse(data)
  if (data.code === 200) {
    file.url = data.data.url
    message.success("上传成功");
  } else {
    message.error(data.data);
  }

  return file;
}

</script>

<template>
  <NLayout has-sider wh-full>
    <section style="padding: 0px;height: 100%;">
      <NLayoutSider content-style="padding: 24px;" :collapsed-width="0" :width="200" show-trigger="arrow-circle"
                    style="border-radius: 10px;height:100%">
        <h1>分类列表</h1>
        <br/>
        <NTree block-line :data="deptOption" key-field="id" label-field="name" default-expand-all
               :node-props="nodeProps" selectable>
        </NTree>
      </NLayoutSider>
    </section>
    <NLayoutContent style="background: transparent;margin-left: 20px;">
      <CommonPage show-footer title="素材列表">
        <template #action>
          <NButton v-permission="'post/api/content/contents/create'" type="primary" @click="handleAdd">
            <TheIcon icon="material-symbols:add" :size="18" class="mr-5"/>
            新建素材
          </NButton>
        </template>
        <!-- 表格 -->
        <CrudTable ref="$table" v-model:query-items="queryItems" :columns="columns" :get-data="api.getContents"
                   :scroll-x="1200">
          <template #queryBar>
            <QueryBarItem label="标题" :label-width="40">
              <NInput v-model:value="queryItems.title" clearable type="text" placeholder="请输入标题"
                      @keypress.enter="$table?.handleSearch()"/>
            </QueryBarItem>
            <QueryBarItem label="类型" :label-width="70">
              <NSelect
                  v-model:value="queryItems.type"
                  style="width: 150px"
                  :options="data.TypeData"
                  clearable
                  placeholder="请选类型"
              />
            </QueryBarItem>
          </template>
        </CrudTable>

        <!-- 新增/编辑 弹窗 -->
        <CrudModal v-model:visible="modalVisible" :title="modalTitle" :loading="modalLoading" @save="handleSave"
                   style="width: 750px !important;">
          <NForm ref="modalFormRef" label-placement="left" label-align="left" :label-width="80"
                 :model="modalForm" :rules="validateAddUser">
            <NFlex justify="space-between">
              <NFormItem label="标题" path="title" style="width: 100%;">
                <NInput v-model:value="modalForm.title" clearable placeholder="请输入标题"/>
              </NFormItem>
              <NFormItem label="排序" path="order">
                <NInputNumber style="width: 200px;" v-model:value="modalForm.order" clearable
                              placeholder="输入排序" :default-value="0"/>
              </NFormItem>

              <NFormItem label="类型" path="type">
                <NSelect style="width: 200px; " v-model:value="modalForm.type" :options="data.TypeData"
                         placeholder="请选择素材类型"/>
              </NFormItem>

              <NFormItem label="素材分类" path="parent">
                <NTreeSelect style="width: 200px;" v-model:value="modalForm.parent"
                             :options="deptOption" key-field="id" label-field="name" placeholder="请选择素材分类"
                             clearable default-expand-all></NTreeSelect>
              </NFormItem>
              <NFormItem label="标签" path="tags">
                <!--                                <NInput v-model:value="modalForm.tags"  clearable placeholder="请输入标签" />-->
                <NSelect style="width: 200px;" v-model:value="modalForm.tags" multiple :options="data.tag_options"
                         placeholder="请输入标签"/>
              </NFormItem>

              <NFormItem label="跳转类型" path="go_type">
                <NSelect style="width: 200px; " v-model:value="modalForm.go_type"
                         :options="data.gotypeData" placeholder="请选择跳转类型"/>
              </NFormItem>
              <NFormItem label="资源值" path="go_url">
                <NInput v-model:value="modalForm.go_url" clearable placeholder="请输入跳转资源值"/>
              </NFormItem>
              <NFormItem label="文章简介" path="desc">
                <NInput style="width: 590px;" type="textarea" v-model:value="modalForm.desc" clearable
                        placeholder="请输入备注"/>
              </NFormItem>


              <NFormItem label="封面图" path="avatar">
                <NImage v-if="modalForm.cover" width="60" style="border-radius: 5px;margin-right: 15px;"
                        :src="modalForm.cover"></NImage>
                <NUpload :action="data.uploadAction" :headers="{ token: data.token }" :max="1" :show-file-list=false
                         :custom-request="customRequestMethod" list-type="image">
                  <NButton>上传</NButton>
                </NUpload>
              </NFormItem>
              <NFormItem label="上传文件" path="files">
                <n-upload multiple directory-dnd v-model:file-list="modalForm.files"
                          :action="data.uploadActions" :headers="{ token: data.token }"
                          @finish="handleFinish" list-type="image">
                  <n-upload-dragger>

                    <n-text style="font-size: 16px">
                      点击或者拖动文件到该区域来上传
                    </n-text>
                    <n-p depth="3" style="margin: 8px 0 0 0">
                      支持格式:JPG,PNG,GIF,MP3,MP4,DOC,DOCX,XLSX,XLS,CSV,PDF
                    </n-p>
                  </n-upload-dragger>
                </n-upload>
              </NFormItem>
            </NFlex>
          </NForm>
        </CrudModal>

      </CommonPage>
    </NLayoutContent>
  </NLayout>
  <!-- 业务页面 -->
</template>
